const positionModel = require('../model/positionModel');
class PositionController {
	constructor() {}
	async save(req, res) {
		let {
			companyName,
			positionName,
			city,
			salary
		} = req.body;
		let positionData = {
			companyLogo: req.imagename,
			companyName,
			positionName,
			city,
			salary
		}
		var rs = await positionModel.save(positionData);
		if (rs) {
			positionController.boradcast('您保存了一条信息');
			res.send({
				code: 1,
				msg: "职位信息保存成功!"
			});
		} else {
			res.send({
				code: 0,
				msg: "职位信息保存失败!"
			})
		}
	}
	
	//根据id删除职位
	async del(req, res, next) {

	    let rs = await positionModel.del(req.query.id);
	    console.log('del rs', rs);
	    if (rs.n && rs.deletedCount) {
	      res.send({ code: 1, msg: '删除成功' });
	    } else {
	      res.send({ code: 0, msg: '删除失败' });
	    }
	
	  }
	
	//根据条件查找职位
	async find(req, res, next) {
		try {
			let list = await positionModel.find(req.query);
			let count = await positionModel.findCount(req.query);
			// console.log(rs);
			res.send({
				datalist: list,
				total: count,
				code: 1
			});
		} catch (error) {
			res.send({
				msg: '请联系管理员',
				code: 0
			});
		}

	}
	//广播
	boradcast(msg){
		for(let o in clientlist){
			clientlist[o].emit('message',msg)
		}
	}
	
	//更新职位数据
	async update(req, res, next) {
	    console.log('position controller', req.imagename)
	    let { companyName, positionName, city, salary, _id } = req.body;
		console.log({ companyName, positionName, city, salary, _id });
	    var rs = await positionModel.update(_id, {
	      companyName,
	      positionName,
	      city,
	      salary,
	      companyLogo: req.imagename
	    })
	    console.log('rs', rs)
	    if (rs.n && rs.nModified) {
			console.log("到这了")
	      res.send({ code: 1, msg: '更新数据成功' })
	    } else {
	      res.send({ code: 0, msg: '更新数据失败' })
	    }
	  }
	 
	//根据id查找一个职位的详细信息
	async findOne(req, res, next) {
	    console.log(req.query)
	    let rs = await positionModel.findOne(req.query.id);
	    // console.log(rs);
	    res.send(rs);
	 }

}
const positionController = new PositionController();
module.exports = positionController;
